<template>
  <div class="review-container">
    <!-- 顶部导航栏 -->
    <div class="header-section">
      <div class="title-container">
        <div class="breadcrumb-title">
          <span class="main-title">活动审核</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button
            type="primary"
            class="back-btn"
            @click="handleBack"
        >
          <el-icon><ArrowLeft /></el-icon>返回队伍管理
        </el-button>
      </div>
    </div>

    <!-- 审核状态选项卡 -->
    <div class="status-tabs">
      <el-card shadow="never" class="tabs-card">
        <el-radio-group v-model="activeStatus" @change="handleStatusChange" class="status-radio-group">
          <el-radio-button label="pending" class="status-radio">
            <el-icon><Clock /></el-icon>
            <span>待审核</span>
            <el-tag type="warning" size="small" effect="dark" class="count-tag">
              {{ pendingCount }}
            </el-tag>
          </el-radio-button>
          <el-radio-button label="approved" class="status-radio">
            <el-icon><CircleCheck /></el-icon>
            <span>审核通过</span>
            <el-tag type="success" size="small" effect="dark" class="count-tag">
              {{ approvedCount }}
            </el-tag>
          </el-radio-button>
          <el-radio-button label="rejected" class="status-radio">
            <el-icon><CircleClose /></el-icon>
            <span>审核不通过</span>
            <el-tag type="danger" size="small" effect="dark" class="count-tag">
              {{ rejectedCount }}
            </el-tag>
          </el-radio-button>
        </el-radio-group>
      </el-card>
    </div>

    <!-- 审核表格 -->
    <el-card class="review-table" shadow="never">
      <el-table
          ref="tableRef"
          :data="pagedData"
          border
          style="width: 100%"
          height="calc(100vh - 320px)"
          @selection-change="handleSelectionChange"
          class="review-data-table"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
            v-if="activeStatus === 'pending'"
            fixed
        />
        <el-table-column prop="index" label="序号" width="80" align="center" fixed />
        <el-table-column prop="teamName" label="队伍名称" width="150" />
        <el-table-column prop="schoolName" label="中学校名" width="150" />
        <el-table-column prop="leaderName" label="队长姓名" width="120" />
        <el-table-column prop="batch" label="母校行批次" width="180" />
        <el-table-column prop="college" label="学院" width="120" />
        <el-table-column prop="contact" label="联系方式" width="150" />
        <el-table-column prop="submitTime" label="提交时间" width="180" />
        <el-table-column label="文件类型" width="150">
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="previewFiles(row)"
                :icon="Files"
                class="file-btn"
            >
              {{ getFileTypeText(row) }}
            </el-button>
          </template>
        </el-table-column>

        <!-- 不通过理由列（仅在rejected状态显示） -->
        <el-table-column
            v-if="activeStatus === 'rejected'"
            label="不通过理由"
            width="200"
        >
          <template #default="{ row }">
            <el-popover
                placement="top-start"
                width="300"
                trigger="hover"
                :content="row.rejectReason || '无理由'"
            >
              <template #reference>
                <div class="reject-reason">
                  <el-tag type="danger" size="small" effect="light">
                    <el-icon><Warning /></el-icon>
                    {{ row.rejectReason || '无理由' | truncate(20) }}
                  </el-tag>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <!-- 操作列（在pending和approved状态显示） -->
        <el-table-column
            v-if="activeStatus !== 'rejected'"
            label="操作"
            width="150"
            align="center"
            fixed="right"
        >
          <template #default="{ row }">
            <el-button
                type="success"
                size="small"
                @click="downloadAll(row)"
                :icon="Download"
                class="download-btn"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部审批按钮和分页 -->
      <div class="table-footer">
        <el-button
            v-if="activeStatus === 'pending'"
            type="primary"
            :disabled="selectedRows.length === 0"
            @click="openApproveDialog"
            class="approve-btn"
            :icon="Finished"
        >
          批量审批({{ selectedRows.length }})
        </el-button>

        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredData.length"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination"
        />
      </div>
    </el-card>

    <!-- 图片预览弹窗 -->
    <el-dialog
        v-model="previewVisible"
        title="活动照片预览"
        width="80%"
        top="5vh"
        class="preview-dialog"
    >
      <el-carousel :interval="4000" height="60vh" indicator-position="outside">
        <el-carousel-item v-for="(item, index) in previewImages" :key="index">
          <div class="carousel-item">
            <el-image
                :src="item"
                :preview-src-list="previewImages"
                :initial-index="index"
                fit="contain"
                style="width: 100%; height: 100%"
            />
            <div class="image-index">图片 {{ index + 1 }}/{{ previewImages.length }}</div>
          </div>
        </el-carousel-item>
      </el-carousel>
      <template #footer>
        <el-button type="primary" @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审批确认弹窗 -->
    <el-dialog
        v-model="approveDialogVisible"
        :title="dialogTitle"
        width="500px"
        center
        class="approve-dialog"
    >
      <div class="approve-dialog-content">
        <div class="dialog-icon">
          <el-icon class="icon-question"><QuestionFilled /></el-icon>
        </div>
        <p class="approve-question">确认审核所选{{ selectedRows.length }}条记录？</p>
        <p class="approve-tip">请确保已仔细检查学生提交的材料</p>
        <div class="approve-buttons">
          <el-button type="success" @click="approve(true)" class="confirm-btn">
            <el-icon><CircleCheck /></el-icon>通过
          </el-button>
          <el-button type="danger" @click="approve(false)" class="reject-btn">
            <el-icon><CircleClose /></el-icon>不通过
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 审批不通过原因弹窗 -->
    <el-dialog
        v-model="rejectDialogVisible"
        title="请输入不通过理由"
        width="500px"
        center
        class="reject-dialog"
    >
      <div class="reject-dialog-content">
        <el-input
            v-model="rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请详细说明不通过的理由，以便学生修改..."
            maxlength="200"
            show-word-limit
        />
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReject" class="submit-btn">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import {
  ArrowLeft,
  Clock,
  CircleCheck,
  CircleClose,
  Files,
  Download,
  Finished,
  Warning,
  QuestionFilled
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 返回按钮处理
const handleBack = () => {
  router.push('/manage/Teammanage')
}

// 审核状态
const activeStatus = ref<'pending' | 'approved' | 'rejected'>('pending')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 表格数据
const reviewData = ref([
  {
    index: 1,
    teamName: '广元一中队',
    schoolName: '广元第一中学',
    leaderName: '张三',
    batch: '母校行活动秋季批次',
    college: '计算机学院',
    contact: '1558888888',
    submitTime: '2023/10/27 00:00:00',
    status: 'pending',
    files: [
      'https://jsj.scujj.edu.cn/sys/FCKFileUpload/AE9E376D1E39AE600A0D743413B881F1.png',
      'https://jsj.scujj.edu.cn/sys/FCKFileUpload/47B9951FC8ED0721139883E170432988.png'
    ],
    rejectReason: ''
  },
  {
    index: 2,
    teamName: '广元第二中队',
    schoolName: '万达中学',
    leaderName: '李四',
    batch: '母校行活动秋季批次',
    college: '艺术学院',
    contact: '1328888999',
    submitTime: '2023/10/28 12:04:02',
    status: 'pending',
    files: [
      'https://jsj.scujj.edu.cn/sys/FCKFileUpload/14B3A5902D1100F79169223569C8E857.png',
      'https://jsj.scujj.edu.cn/sys/FCKFileUpload/48E0D4004CCFBE575CE4725F73C64E74.png'
    ],
    rejectReason: ''
  },
  {
    index: 3,
    teamName: '创新队',
    schoolName: '实验中学',
    leaderName: '王五',
    batch: '母校行活动春季批次',
    college: '理学院',
    contact: '1399999999',
    submitTime: '2023/04/15 09:30:00',
    status: 'approved',
    files: '附件',
    rejectReason: ''
  },
  {
    index: 4,
    teamName: '探索队',
    schoolName: '外国语学校',
    leaderName: '赵六',
    batch: '母校行活动春季批次',
    college: '文学院',
    contact: '1366666666',
    submitTime: '2023/04/20 14:15:00',
    status: 'rejected',
    files: '附件',
    rejectReason: '照片不符合要求，请重新上传活动照片'
  }
])

// 计算各状态数量
const pendingCount = computed(() => reviewData.value.filter(item => item.status === 'pending').length)
const approvedCount = computed(() => reviewData.value.filter(item => item.status === 'approved').length)
const rejectedCount = computed(() => reviewData.value.filter(item => item.status === 'rejected').length)

// 获取文件类型文本
const getFileTypeText = (row: any) => {
  if (Array.isArray(row.files)) {
    return row.files.length > 0 ? `${row.files.length}张图片` : '无'
  }
  return '附件'
}

// 表格ref
const tableRef = ref<any>(null)

// 选中的行
const selectedRows = ref<any[]>([])

// 表格选择变化处理
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val
}

// 过滤后的数据
const filteredData = computed(() => {
  return reviewData.value.filter(item => {
    if (activeStatus.value === 'pending') return item.status === 'pending'
    if (activeStatus.value === 'approved') return item.status === 'approved'
    return item.status === 'rejected'
  })
})

// 分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 弹窗标题
const dialogTitle = computed(() => {
  return `批量审批 (${selectedRows.value.length}条)`
})

// 状态切换
const handleStatusChange = () => {
  currentPage.value = 1
  tableRef.value?.clearSelection()
}

// 预览相关
const previewVisible = ref(false)
const previewImages = ref<string[]>([])

const previewFiles = (row: any) => {
  if (Array.isArray(row.files)) {
    if (row.files.length === 0) {
      ElMessage.warning('暂无图片可预览')
      return
    }
    previewImages.value = row.files
    previewVisible.value = true
  } else {
    ElMessage.warning('此文件为附件，不支持预览')
  }
}

// 审批相关
const approveDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const rejectReason = ref('')

const openApproveDialog = () => {
  if (selectedRows.value.length === 0) return
  approveDialogVisible.value = true
}

const approve = (isApproved: boolean) => {
  approveDialogVisible.value = false
  if (isApproved) {
    selectedRows.value.forEach(row => {
      row.status = 'approved'
      row.rejectReason = ''
    })
    ElNotification({
      title: '审批通过',
      message: `已通过${selectedRows.value.length}条记录`,
      type: 'success',
      duration: 2000
    })
    tableRef.value?.clearSelection()
    selectedRows.value = []
  } else {
    rejectReason.value = ''
    rejectDialogVisible.value = true
  }
}

const submitReject = () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请输入不通过理由')
    return
  }
  selectedRows.value.forEach(row => {
    row.status = 'rejected'
    row.rejectReason = rejectReason.value
  })
  ElNotification({
    title: '审批不通过',
    message: `已拒绝${selectedRows.value.length}条记录`,
    type: 'warning',
    duration: 2000
  })
  rejectDialogVisible.value = false
  rejectReason.value = ''
  tableRef.value?.clearSelection()
  selectedRows.value = []
}

// 下载相关
const downloadAll = (row: any) => {
  ElMessage.success(`开始下载 ${row.teamName} 的所有文件`)
}

// 文本截断过滤器
const truncate = (value: string, length: number) => {
  if (!value) return ''
  if (value.length <= length) return value
  return value.substring(0, length) + '...'
}
</script>

<style scoped lang="scss">
.review-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  gap: 16px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  .title-container {
    .breadcrumb-title {
      display: flex;
      align-items: center;

      .main-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: "";
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }
    }
  }

  .back-btn {
    padding: 8px 15px;
    border-radius: 6px;

    .el-icon {
      margin-right: 5px;
    }
  }
}

.status-tabs {
  .tabs-card {
    border-radius: 8px;
    border: none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    :deep(.el-card__body) {
      padding: 12px 16px;
    }

    .status-radio-group {
      display: flex;
      width: 100%;

      .status-radio {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px 0;
        border: none !important;
        background-color: transparent !important;

        &:hover {
          background-color: #f5f7fa !important;
        }

        &.is-active {
          background-color: #ecf5ff !important;
          color: #409EFF;
        }

        .el-icon {
          margin-right: 8px;
          font-size: 16px;
        }

        .count-tag {
          margin-left: 8px;
        }
      }
    }
  }
}

.review-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  :deep(.el-card__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .review-data-table {
    flex: 1;

    :deep(.el-table__header-wrapper) {
      .el-table__header {
        th {
          background-color: #f5f7fa;
          font-weight: 600;
          color: #606266;
        }
      }
    }

    :deep(.el-table__body-wrapper) {
      .el-table__body {
        tr:hover > td {
          background-color: #f5f7fa !important;
        }
      }
    }

    .file-btn {
      padding: 5px 10px;
    }

    .download-btn {
      padding: 5px 10px;
    }

    .reject-reason {
      .el-tag {
        max-width: 180px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #ebeef5;

    .approve-btn {
      padding: 8px 15px;

      .el-icon {
        margin-right: 5px;
      }
    }

    .pagination {
      margin: 0;
    }
  }
}

.preview-dialog {
  border-radius: 8px;

  :deep(.el-dialog__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-weight: 600;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 0;

    .carousel-item {
      position: relative;
      height: 100%;

      .image-index {
        position: absolute;
        bottom: 20px;
        right: 20px;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 14px;
      }
    }
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.approve-dialog {
  border-radius: 8px;

  .approve-dialog-content {
    text-align: center;
    padding: 20px;

    .dialog-icon {
      margin-bottom: 20px;

      .icon-question {
        font-size: 48px;
        color: #409EFF;
      }
    }

    .approve-question {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 8px;
    }

    .approve-tip {
      font-size: 14px;
      color: #909399;
      margin-bottom: 24px;
    }

    .approve-buttons {
      display: flex;
      justify-content: center;
      gap: 24px;

      .confirm-btn, .reject-btn {
        padding: 10px 24px;

        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }
}

.reject-dialog {
  border-radius: 8px;

  .reject-dialog-content {
    padding: 20px;

    :deep(.el-textarea__inner) {
      min-height: 120px !important;
    }

    .dialog-footer {
      margin-top: 20px;
      text-align: right;

      .submit-btn {
        padding: 8px 20px;
      }
    }
  }
}

@media (max-width: 992px) {
  .status-tabs {
    .status-radio-group {
      flex-direction: column;

      .status-radio {
        margin-bottom: 8px;
      }
    }
  }
}

@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .header-actions {
      width: 100%;

      .back-btn {
        width: 100%;
      }
    }
  }

  .table-footer {
    flex-direction: column;
    gap: 12px;

    .approve-btn {
      width: 100%;
    }

    .pagination {
      width: 100%;
      justify-content: center;
    }
  }

  .preview-dialog {
    width: 90% !important;
  }
}
</style>